package com.zx.crowdfunding.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.google.gson.Gson;
import com.zx.crowdfunding.constant.CrowdFundingConstant;
import com.zx.crowdfunding.util.CrowdFundingUtil;
import com.zx.crowdfunding.util.ResultEntity;

/**
 * 自定义的SpringSecurity访问被拒绝的异常处理器
 * @author 郑雪
 * @date 2021-12-14
 */
public class CrowdFundingAccessDeniedHandler implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request,
			HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException,
			ServletException {
		
		accessDeniedException = new AccessDeniedException(CrowdFundingConstant.MESSAGE_ACCESS_DENIED);
		
		// 1.判断当前请求类型
		boolean judgeRequest = CrowdFundingUtil.judgeRequestType(request);
		
		// 2.如果是Ajax请求
		if(judgeRequest){
			
			// 3.创建ResultEntity对象
			ResultEntity<Object> resultEntity = ResultEntity.failed(accessDeniedException.getMessage());
			
			// 4.创建Gson对象
			Gson gson = new Gson();
			
			// 5.将ResultEntity对象转换为JSON字符串
			String json = gson.toJson(resultEntity);
			
			// 6.将JSON字符串作为响应体返回给浏览器
			response.getWriter().write(json);
			
		}else{
			
			// 7.将Exception对象放入请求域中
			request.setAttribute(CrowdFundingConstant.ATTR_NAME_EXCEPTION, accessDeniedException);
			
			// 8.跳转页面路径
			String toPath = "/WEB-INF/system-error.jsp";
			
			// 9.将请求地址转发到系统错误页面
			request.getRequestDispatcher(toPath).forward(request, response);
		}
	}

}
